package com.atguigui.leetcode;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;

/**
 * 636.函数的独占时间
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/8/7 8:33
 */
public class P636ExclusiveTimeOfFunctions {
    public static void main(String[] args) {
        Solution solution = new P636ExclusiveTimeOfFunctions().new Solution();
        // TO TEST
    }

    class Solution {
        public int[] exclusiveTime(int n, List<String> logs) {
            Deque<int[]> stack = new ArrayDeque<int[]>(); // {idx, 开始运行的时间}
            int[] res = new int[n];

            for (String log : logs) {
                //截图id
                int idx = Integer.parseInt(log.substring(0, log.indexOf(':')));
                String type = log.substring(log.indexOf(':') + 1, log.lastIndexOf(':'));
                //时间
                int timestamp = Integer.parseInt(log.substring(log.lastIndexOf(':') + 1));
                //入栈
                if ("start".equals(type)) {
                    if (!stack.isEmpty()) {
                        res[stack.peek()[0]] += timestamp - stack.peek()[1];
                        //更新入栈时间
                        stack.peek()[1] = timestamp;
                    }
                    stack.push(new int[]{idx, timestamp});
                } else {
                    int[] t = stack.pop();
                    //时间累加
                    res[t[0]] += timestamp - t[1] + 1;
                    if (!stack.isEmpty()) {
                        stack.peek()[1] = timestamp + 1;
                    }
                }
            }
            return res;
        }
    }
}
